package com.java2007.web.controller;

import com.java2007.pojo.Admin;
import com.java2007.pojo.ReaderCard;
import com.java2007.service.AdminService;
import com.java2007.service.ReaderCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zy
 * @version V1.0
 * @date 2021/03/10
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private ReaderCardService readerCardService;

    /**
     * 显示登录页面
     * @return
     */
    @GetMapping({"/","/login.html","/tologinui"})
    public String toLoginUI(){
        return "index";
    }

    /**
     * 登录
     * @param id
     * @param passwd
     * @param session
     * @return
     */
    @PostMapping("/api/loginCheck")
    @ResponseBody
    public Map<String,String> loginCheck(String id, String passwd, HttpSession session){
        log.info("id ：{}",id);
        log.info("passwd : {}",passwd);

        Map<String,String> map = new HashMap<>();
        map.put("stateCode","0");

        try {
            Admin admin = adminService.login(id, passwd);
            session.setAttribute("admin", admin);
            map.put("stateCode","1");
        } catch (Exception e) {
            e.printStackTrace();
            //读者登录
            try {
                ReaderCard readerCard = readerCardService.login(id, passwd);
                session.setAttribute("readerCard",readerCard);
                map.put("stateCode","2");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @GetMapping({"/logout","/logout.html"})
    public String logout(HttpSession session){
        session.invalidate();
        return "index";
    }
}
